<?php

/**
 * This is the model class for table "Offer".
 *
 * The followings are the available columns in table 'Offer':
 * @property integer $offer_id
 * @property integer $business_id
 * @property string $offer_name
 * @property double $price
 * @property string $offer_detail
 * @property string $voice
 * @property string $video
 * @property string $image_id
 * @property string $start_date
 * @property string $expiry_date
 * @property integer $offer_status
 */
class Offer extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Offer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'offer';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('business_id, offer_detail, start_date, expiry_date', 'required'),
			array('business_id, offer_status', 'numerical', 'integerOnly'=>true),
            array('start_date, expiry_date',  'safe'),
			array('price', 'numerical'),
			array('offer_name, image_id', 'length', 'max'=>50),
			array('voice, video', 'length', 'max'=>1),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('offer_id, business_id, offer_name, price, offer_detail, voice, video, image_id, start_date, expiry_date, offer_status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'business' => array(self::BELONGS_TO, 'Business', 'business_id'),
		);
	}

    /**
     * @return override the CActiveRecord::defaultScope method, so that only display user's own record.
     * id used here is the business id stored in account table
     */
    public function defaultScope()
    {
        return array(
            'condition'=>'business_id='.Yii::app()->user->id,
        );
    }

    /**
     * @return convert php date format to mysql date format
     */
    public function beforeSave()
    {
        //PHP dates are displayed as mm/dd/yyyy
        //MYSQL dates are stored as yyyy-mm-dd
        // convert to storage format, at moment "this->start_date and expiry_date is empty"
        //$this->start_date='12/23/2012';
        //http://www.yiiframework.com/forum/index.php/topic/12151-how-to-access-to-a-model-attribute-in-beforesave-method/
        if ($this->IsNewRecord){
            //adding new record, do nothing
            Yii::trace("Adding dummy records... or record is unchanged");
        }else{
            //updating record, reformat date for mysql
            Yii::trace("Model-BeforeSaveDate1:".$this->start_date);
            Yii::trace("Model-BeforeSaveDate2:".$this->expiry_date);

            //transfer the picture from temp directory in business to its final destination.
            Yii::trace("Image file name:".$this->image_id);
            Yii::trace("copy dest location:".$this->business->home_url);
            Yii::trace("copy source location sessionid:".session_id());

            //if tempfile exist, then move it to target folder.
            //base directory for target :http://localhost/h5vofdyr/index.php
            //base directory for business :http://localhost/mbusiness/index.php

            $targetClient=substr(parse_url($this->business->home_url, PHP_URL_PATH), 1, 8);
            $thumbnail = realpath(Yii::app()->getBasePath().'/..').DIRECTORY_SEPARATOR.'server'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.session_id().DIRECTORY_SEPARATOR.'thumbnail'.DIRECTORY_SEPARATOR.$this->image_id;

            if (file_exists($thumbnail)) {
                //for linux, offerImage path should be '/../..', windows, path is '../../..'
                if( strcasecmp(Yii::app()->params['HostOS'], "linux")==0){
                    $offerImage = realpath(Yii::app()->getBasePath().'/../..').DIRECTORY_SEPARATOR.$targetClient.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'offers'.DIRECTORY_SEPARATOR.$this->image_id;
                }else{
                    $offerImage = realpath(Yii::app()->getBasePath().'../../..').DIRECTORY_SEPARATOR.$targetClient.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'offers'.DIRECTORY_SEPARATOR.$this->image_id;
                }

                Yii::trace("beginning to copy $thumbnail to...".$offerImage);
                if (!copy($thumbnail, $offerImage)) {
                    Yii::trace("failed to copy $thumbnail...");
                }
            }else{
                Yii::trace("file $thumbnail doesn't exist...");
            }

            $start=DateTime::createFromFormat('m/d/Y',$this->start_date);
            $this->start_date=$start->format('Y-m-d');

            //$this->expiry_date='12/30/2012';
            $end=DateTime::createFromFormat('m/d/Y',$this->expiry_date);
            $this->expiry_date=$end->format('Y-m-d');

            Yii::trace("BeforeSaveDate1:".$this->start_date);
            Yii::trace("BeforeSaveDate2:".$this->expiry_date);
        }
        return parent::beforeSave();

    }

    /**
     * @return convert form saved date back to mm/dd/yyyy
     */
    public function afterSave()
    {
        if ($this->IsNewRecord){
            //adding new record, do nothing
            Yii::trace("Adding dummy records...");
        }else{
            $from=DateTime::createFromFormat('Y-m-d',$this->start_date);
            $this->start_date=$from->format('m/d/Y');

            $to=DateTime::createFromFormat('Y-m-d',$this->expiry_date);
            $this->expiry_date=$to->format('m/d/Y');

        }
        return parent::afterSave();

    }

    /**
     * @return convert mysql date format to php date format
     */
    public function afterFind()
    {
        //PHP dates are displayed as mm/dd/yyyy
        //MYSQL dates are stored as yyyy-mm-dd
        // convert to display format
        $from=DateTime::createFromFormat('Y-m-d',$this->start_date);
        $this->start_date=$from->format('m/d/Y');

        $to=DateTime::createFromFormat('Y-m-d',$this->expiry_date);
        $this->expiry_date=$to->format('m/d/Y');

        return parent::afterFind();

    }

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'offer_id' => 'Offer',
			'business_id' => 'Business',
			'offer_name' => 'Offer Name',
			'price' => 'Price',
			'offer_detail' => 'Offer Detail',
			'voice' => 'Voice',
			'video' => 'Video',
			'image_id' => 'Image',
			'start_date' => 'Start Date',
			'expiry_date' => 'Expiry Date',
			'offer_status' => 'Offer Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('offer_id',$this->offer_id);
		$criteria->compare('business_id',$this->business_id);
		$criteria->compare('offer_name',$this->offer_name,true);
		$criteria->compare('price',$this->price);
		$criteria->compare('offer_detail',$this->offer_detail,true);
		$criteria->compare('voice',$this->voice,true);
		$criteria->compare('video',$this->video,true);
		$criteria->compare('image_id',$this->image_id,true);
		$criteria->compare('start_date',$this->start_date,true);
		$criteria->compare('expiry_date',$this->expiry_date,true);
		$criteria->compare('offer_status',$this->offer_status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}